package capimServer;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class CapimServer {
	
	private static int clientPort;
	public static int port;
	public static SendPackets postOffice;
	public static ReceivePackets Server;
	
	/**
	 * Main class
	 * @param args if 'startDB' initialize the DataBase
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		setClientPort(8911);
		if(args.length > 0 ){
			if(args[0].equals("startDB")){
				System.out.println("Starting DataBase.");
				DB start = new DB();
				start.startDB();
			}
		}
		
		// set configuration
		
		setConfig();
		System.out.println("Starting to listen...");
		Server = new ReceivePackets();
		postOffice = new SendPackets();

	}
	
	/**
	 * Read the config file ('config') and set apropriate values
	 */
	static public void setConfig(){
		// TODO Read more config options
		FileInputStream configFile = null;
		BufferedInputStream bConfigFile = null;
		StringBuffer sport = null;
		
		try{
			configFile = new FileInputStream("config");
			bConfigFile = new BufferedInputStream(configFile);
			sport = new StringBuffer();
			
			int in = 0;
			char inChar;
			
			do {
				in = bConfigFile.read();
				inChar = (char) in;
				
				if((in != -1)&(in!='\n')&(in!='\r')){
					sport.append(inChar);
				}
				
			} while (in != -1);
			
			port = Integer.parseInt(sport.toString());
			
		} catch (FileNotFoundException e){
			System.out.println("Config File 'config' not fount.");
			System.exit(-1);
		} catch (IOException e1){
			e1.printStackTrace();
		}
		
	}

	public static void setClientPort(int clientPort) {
		CapimServer.clientPort = clientPort;
	}

	public static int getClientPort() {
		return clientPort;
	}

}
